﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;

namespace FaceService.WebAPI.Controllers.FaceInfo;

[Route("[Controller]")]
[ApiController]
[Authorize(Roles = "Admin")]
public class FaceInfoController : ControllerBase
{
    private readonly IFIService _ifiService;

    public FaceInfoController(IFIService ifiService)
    {
        _ifiService = ifiService;
    }

    [HttpGet]
    public async Task<ActionResult<FaceRecognizer>> GetFace([FromQuery] GetFaceRequest getFace)
    {
        string search = "";
        if (!getFace.Search.IsNullOrEmpty())
                search = getFace.Search!;
        var faces = await _ifiService.GetAllAsync(search, getFace.PageNo, getFace.PageSize);
        var total = await _ifiService.GetAllTotalAsync(search);
        if (faces is null) return NotFound(new { Code = 404, Msg = "未能找到人脸数据" });
        return Ok(new { Code = 200, Data =  new { PageData = faces, Total = total}, Msg = "查询成功" });
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetFaceById(Guid id)
    {
        var face = await _ifiService.GetByIdAsync(id);
        if (face is null) return NotFound(new { Code = 404, Msg = "未能找到人脸数据" });
        return Ok(new { Code = 200, Data = face, Msg = "查询成功" });
    }

    [HttpPost]
    public async Task<ActionResult<FaceRecognizer>> Created(CreatedFaceRequest creaatedFace)
    {
        var face = await _ifiService.CreatedAsync(creaatedFace.Name, creaatedFace.Image, creaatedFace.StudentId);
        return Ok(new { Code = 200, Data = face, Msg = "创建成功" });
    }

    [HttpPut("{id:guid}")]
    public async Task<ActionResult<FaceRecognizer>> Updated(Guid id, UpdatedFaceRequest updatedFace)
    {
        if (id != updatedFace.Id) return BadRequest(new { Code = 400, Msg = "参数错误" });
        var face = await _ifiService.UpdatedAsync(updatedFace.Id, updatedFace.Name, updatedFace.Image,
            updatedFace.StudentId);
        if (face is null) return NotFound(new { Code = 404, Msg = "未能找到人脸数据" });
        return Ok(new { Code = 200, Msg = "更新成功" });
    }

    [HttpDelete("{id:guid}")]
    public async Task<IActionResult> Deleted(Guid id)
    {
        var gid = await _ifiService.DeletedByIdAsync(id);
        if (gid is null) return NotFound(new { Code = 404, Msg = "未能找到人脸数据" });
        return Ok(new { Code = 200, Msg = "删除成功" });
    }

    [HttpPost]
    [Route("[Action]")]
    public async Task<IActionResult> Search(SearchFaceRequest searchFace)
    {
        var faces = await _ifiService.SearchFaceAsync(searchFace.Image);
        return Ok(new { Code = 200, Data = faces, Msg = "查询成功" });
    }
}
